package com.xpengplayer.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentManager;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.view.SurfaceHolder;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.content.pm.ActivityInfo;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.view.SurfaceHolder;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.xpengplayer.R;
import com.xpengplayer.data.PlayHistory;
import com.xpengplayer.data.PlayHistoryManager;
import com.xpengplayer.update.UpdateChecker;
import com.xpengplayer.update.UpdateDialog;
import com.xpengplayer.update.UpdateInfo;
import com.xpengplayer.update.UpdateManager;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_READ_STORAGE = 1;
    private static final int PERMISSION_REQUEST_MANAGE_STORAGE = 2;
    private static final int FILE_SELECT_CODE = 3;

    private PlayerView playerView;
    private SimpleExoPlayer player;
    private Button playPauseButton;
    private Button chooseFileButton;
    private Button fullscreenButton;
    private Button exitFullscreenButton;
    private Button backToMainButton; // 返回主界面按钮
    private Button rewindButton; // 快退按钮
    private Button fastForwardButton; // 快进按钮
    private Button muteButton; // 静音按钮
    private boolean isMuted = false; // 是否静音
    private SeekBar progressBar;
    private TextView currentTimeView;
    private TextView totalTimeView;
    private TextView videoTitleView;
    private Button speedButton; // 倍速控制按钮
    private View customControls;
    private View mainContainer;
    private View topControlLayout;
    private View bottomControlLayout;

    private boolean isFullscreen = false;
    private boolean isControlsVisible = false; // 控制栏是否可见
    private Uri currentVideoUri = null;
    private Timer progressTimer;
    private Timer hideControlsTimer; // 控制栏隐藏计时器
    private ArrayAdapter<CharSequence> speedAdapter;
    private final float[] playbackSpeeds = {0.5f, 0.7f, 1.0f, 1.25f, 1.5f, 1.75f, 2.0f, 3.0f};
    private int currentSpeedIndex = 2; // 默认为1.0x速度
    private Button settingsButton;
    private List<String> sameDirectoryVideos = new ArrayList<>();
    private int currentVideoIndex = -1;
    private MainContentFragment mainContentFragment;
    private PlayHistoryManager historyManager;
    private UpdateChecker updateChecker;
    private UpdateManager updateManager;
    private UpdateDialog updateDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化视图组件
        playerView = findViewById(R.id.player_view);
        playPauseButton = findViewById(R.id.play_pause_button);
        // choose_file_button不存在，移除这个引用
        settingsButton = findViewById(R.id.settings_button);
        fullscreenButton = findViewById(R.id.fullscreen_button);
        exitFullscreenButton = findViewById(R.id.exit_fullscreen_button);
        // 尝试找到返回主界面按钮（如果存在）
        backToMainButton = findViewById(R.id.back_to_main_button);
        // 尝试找到快退和快进按钮
        rewindButton = findViewById(R.id.rewind_button);
        fastForwardButton = findViewById(R.id.fast_forward_button);
        // 尝试找到静音按钮
        muteButton = findViewById(R.id.mute_button);
        progressBar = findViewById(R.id.progress_bar);
        currentTimeView = findViewById(R.id.current_time);
        totalTimeView = findViewById(R.id.total_time);
        videoTitleView = findViewById(R.id.video_title);
        // 使用Button替代Spinner作为倍速控制
        speedButton = findViewById(R.id.speed_button);
        customControls = findViewById(R.id.custom_controls);
        mainContainer = findViewById(R.id.main_container);
        playerView = findViewById(R.id.player_view); // 使用player_view替代player_container
        topControlLayout = findViewById(R.id.top_control_layout); // 使用正确的ID
        bottomControlLayout = findViewById(R.id.bottom_control_layout); // 使用正确的ID
        
        // 初始化管理器
        historyManager = new PlayHistoryManager(this);
        
        // 添加主内容Fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        mainContentFragment = new MainContentFragment();
        fragmentManager.beginTransaction()
                .replace(R.id.content_container, mainContentFragment)
                .commit();
        
        // 设置视频选择监听器
        mainContentFragment.setOnVideoSelectListener(videoUri -> {
            // 隐藏主内容，显示播放器
            findViewById(R.id.content_container).setVisibility(View.GONE);
            playerView.setVisibility(View.VISIBLE);
            customControls.setVisibility(View.VISIBLE);
            isControlsVisible = true;
            
            // 准备播放器
            preparePlayer(videoUri);
        });

        // 初始化倍速选择器
        speedAdapter = ArrayAdapter.createFromResource(this, R.array.playback_speeds, android.R.layout.simple_spinner_item);
        speedAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // 使用Button替代Spinner作为倍速控制
        if (speedButton != null) {
            speedButton.setText(String.format("%.1fx", playbackSpeeds[currentSpeedIndex])); // 默认显示1.0x速度
        }

        // 设置事件监听器
        playPauseButton.setOnClickListener(v -> {
            togglePlayPause();
            resetHideControlsTimer(); // 重置隐藏计时器
        });
        
        // 设置快退按钮监听
        if (rewindButton != null) {
            rewindButton.setOnClickListener(v -> {
                rewind();
                resetHideControlsTimer(); // 重置隐藏计时器
            });
        }
        
        // 设置快进按钮监听
        if (fastForwardButton != null) {
            fastForwardButton.setOnClickListener(v -> {
                fastForward();
                resetHideControlsTimer(); // 重置隐藏计时器
            });
        }
        
        // 设置静音按钮监听
        if (muteButton != null) {
            muteButton.setOnClickListener(v -> {
                toggleMute();
                resetHideControlsTimer(); // 重置隐藏计时器
            });
        }
        // 添加null检查，防止空指针异常
        if (chooseFileButton != null) {
            chooseFileButton.setOnClickListener(v -> {
                // 隐藏播放器，显示文件选择界面
                Intent intent = new Intent(MainActivity.this, DirectoryBrowserActivity.class);
                startActivityForResult(intent, 100);
            });
        }
        settingsButton.setOnClickListener(v -> openSettings());
        fullscreenButton.setOnClickListener(v -> {
            enterFullscreen();
            resetHideControlsTimer(); // 重置隐藏计时器
        });
        exitFullscreenButton.setOnClickListener(v -> {
            exitFullscreen();
            resetHideControlsTimer(); // 重置隐藏计时器
        });
        
        // 设置返回主界面按钮监听
        if (backToMainButton != null) {
            backToMainButton.setOnClickListener(v -> returnToMainScreen());
        }
        
        // 为播放器视图添加触摸事件，用于显示/隐藏控制栏
        playerView.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                toggleControlsVisibility();
                return true;
            }
            return false;
        });
        
        // 为控制栏添加触摸事件，防止点击控制栏时隐藏
        customControls.setOnTouchListener((v, event) -> {
            resetHideControlsTimer();
            return false;
        });
        progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && player != null) {
                    long seekPosition = (long) (progress * player.getDuration() / 100);
                    player.seekTo(seekPosition);
                    resetHideControlsTimer(); // 重置隐藏计时器
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                stopProgressTimer();
                resetHideControlsTimer(); // 重置隐藏计时器
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                startProgressTimer();
                resetHideControlsTimer(); // 重置隐藏计时器
            }
        });

        // 设置倍速按钮点击监听器
        if (speedButton != null) {
            speedButton.setOnClickListener(v -> {
                if (player != null) {
                    // 循环切换到下一个速度
                    currentSpeedIndex = (currentSpeedIndex + 1) % playbackSpeeds.length;
                    player.setPlaybackSpeed(playbackSpeeds[currentSpeedIndex]);
                    speedButton.setText(String.format("%.1fx", playbackSpeeds[currentSpeedIndex]));
                    resetHideControlsTimer(); // 重置隐藏计时器
                }
            });
        }

        // 处理从其他应用打开的视频文件
        handleIntent(getIntent());
        
        // 初始化更新检查器
        updateManager = UpdateManager.getInstance(this);
        updateChecker = UpdateChecker.getInstance(this);
        
        // 设置更新回调
        updateManager.setUpdateCallback(new UpdateManager.UpdateCallback() {
            @Override
            public void onUpdateAvailable(UpdateInfo updateInfo) {
                // 发现新版本，显示更新对话框
                showUpdateDialog(updateInfo);
            }
            
            @Override
            public void onUpdateNotAvailable() {
                // 没有新版本，不需要处理
            }
            
            @Override
            public void onNoUpdate() {
                // 没有更新，与onUpdateNotAvailable功能类似，不需要特别处理
            }
            
            @Override
            public void onError(String errorMessage) {
                // 检查更新出错，不显示错误信息以避免打扰用户
                // 可以选择记录日志
            }
            
            @Override
            public void onDownloadProgress(int progress, long bytesDownloaded, long totalBytes) {
                // 更新进度在UpdateDialog中处理
            }
            
            @Override
            public void onDownloadComplete(File apkFile) {
                // 下载完成在UpdateDialog中处理
            }
            
            @Override
            public void onDownloadFailed(String errorMessage) {
                // 下载失败在UpdateDialog中处理
            }
        });
        
        // 延迟几秒钟后检查更新，避免应用启动时阻塞UI
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                checkForUpdates();
            }
        }, 3000);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        if (intent != null && intent.getAction() != null && intent.getAction().equals(Intent.ACTION_VIEW)) {
            Uri uri = intent.getData();
            if (uri != null) {
                preparePlayer(uri);
            }
        }
    }
    
    /**
     * 检查应用更新
     */
    private void checkForUpdates() {
        // 读取用户设置
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        boolean shouldAutoCheck = preferences.getBoolean("pref_auto_check_updates", true);
        boolean wifiOnly = preferences.getBoolean("pref_check_updates_on_wifi_only", true);
        
        // 如果用户关闭了自动检查更新，则不执行
        if (!shouldAutoCheck) {
            return;
        }
        
        // 如果设置了仅在WiFi下检查更新，则检查当前网络状态
        if (wifiOnly && !isWifiConnected()) {
            return;
        }
        
        // 开始检查更新
        updateChecker.checkForUpdates();
    }
    
    /**
     * 检查当前是否连接到WiFi网络
     * @return 如果当前连接到WiFi返回true，否则返回false
     */
    private boolean isWifiConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected();
        }
        return false;
    }
    
    /**
     * 显示更新对话框
     */
    private void showUpdateDialog(UpdateInfo updateInfo) {
        if (updateDialog != null && updateDialog.isShowing()) {
            updateDialog.dismiss();
        }
        
        // 创建更新对话框
        updateDialog = new UpdateDialog(this, updateInfo, updateManager);
        updateDialog.setOnUpdateListener(new UpdateDialog.OnUpdateListener() {
            @Override
            public void onUpdate() {
                // 用户点击更新按钮
                updateManager.downloadApk(updateInfo.getApkUrl());
            }
            
            @Override
            public void onCancel() {
                // 用户取消更新
                // 如果是强制更新，则不能取消
                if (updateInfo.isForceUpdate()) {
                    finish(); // 强制更新时，如果用户取消，关闭应用
                }
            }
            
            @Override
            public void onRetry() {
                // 用户点击重试按钮
                updateManager.downloadApk(updateInfo.getApkUrl());
            }
        });
        
        // 显示对话框
        updateDialog.show();
    }

    private void requestStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11及以上需要特殊权限
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                startActivityForResult(intent, PERMISSION_REQUEST_MANAGE_STORAGE);
            } else {
                openFilePicker();
            }
        } else {
            // Android 10及以下使用传统权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_READ_STORAGE);
            } else {
                openFilePicker();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_READ_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openFilePicker();
            } else {
                Toast.makeText(this, R.string.permission_storage_rationale, Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri selectedUri = data.getData();
            // 隐藏主内容，显示播放器
            findViewById(R.id.content_container).setVisibility(View.GONE);
            playerView.setVisibility(View.VISIBLE);
            customControls.setVisibility(View.VISIBLE);
            isControlsVisible = true;
            
            preparePlayer(selectedUri);
        } else if (requestCode == PERMISSION_REQUEST_MANAGE_STORAGE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    openFilePicker();
                } else {
                    Toast.makeText(this, R.string.permission_manage_storage_rationale, Toast.LENGTH_LONG).show();
                }
            }
        } else if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
            // 从DirectoryBrowserActivity返回
            String videoPath = data.getStringExtra(DirectoryBrowserActivity.EXTRA_SELECTED_VIDEO_PATH);
            if (videoPath != null) {
                // 隐藏主内容，显示播放器
                findViewById(R.id.content_container).setVisibility(View.GONE);
                playerView.setVisibility(View.VISIBLE);
                customControls.setVisibility(View.VISIBLE);
                isControlsVisible = true;
                
                Uri videoUri = Uri.fromFile(new File(videoPath));
                preparePlayer(videoUri);
            }
        }
    }

    private void openFilePicker() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("video/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{"video/mp4", "video/*"});
        startActivityForResult(intent, FILE_SELECT_CODE);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if ((Util.SDK_INT < 24 || player == null) && currentVideoUri != null) {
            preparePlayer(currentVideoUri);
        }
        
        // 如果没有正在播放的视频，显示主内容Fragment
        if (currentVideoUri == null) {
            findViewById(R.id.content_container).setVisibility(View.VISIBLE);
            playerView.setVisibility(View.GONE);
            customControls.setVisibility(View.GONE);
        }
    }

    private void preparePlayer(Uri videoUri) {
        // 释放之前的播放器实例
        releasePlayer();

        currentVideoUri = videoUri;

        // 获取文件名并显示
        String fileName = getFileName(videoUri);
        videoTitleView.setText(fileName);
        
        // 保存播放历史
        String videoPath = videoUri.toString();
        PlayHistory history = new PlayHistory(videoPath, fileName);
        historyManager.addOrUpdateHistory(history);
        
        // 获取同目录下的视频文件列表
        loadSameDirectoryVideos(videoUri);

        // 创建ExoPlayer实例
        DefaultTrackSelector trackSelector = new DefaultTrackSelector(this);
        player = new SimpleExoPlayer.Builder(this)
                .setTrackSelector(trackSelector)
                .build();

        // 绑定到PlayerView
        playerView.setPlayer(player);

        // 创建媒体源
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this, 
                Util.getUserAgent(this, "XpengPlayer"));
        MediaSource mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
                .createMediaSource(MediaItem.fromUri(videoUri));

        // 准备播放器
        player.prepare(mediaSource);
        player.setPlayWhenReady(false);

        // 设置播放状态监听器
        player.addListener(new Player.Listener() {
            @Override
            public void onPlaybackStateChanged(int state) {
                if (state == Player.STATE_READY) {
                    updatePlayPauseButton();
                    updateTotalTime();
                    startProgressTimer();
                    // 开始控制栏隐藏计时
                    startHideControlsTimer();
                } else if (state == Player.STATE_ENDED) {
                    playPauseButton.setText(R.string.play);
                    stopProgressTimer();
                    stopHideControlsTimer(); // 停止隐藏计时器
                    
                    // 检查是否启用了连播
                    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                    boolean autoPlayNext = preferences.getBoolean("auto_play_next", true);
                    
                    if (autoPlayNext) {
                        playNextVideo();
                    }
                } else if (state == Player.STATE_BUFFERING) {
                    // 缓冲中
                } else if (state == Player.STATE_IDLE) {
                    playPauseButton.setText(R.string.play);
                    stopHideControlsTimer(); // 停止隐藏计时器
                }
            }

            @Override
            public void onIsPlayingChanged(boolean isPlaying) {
                updatePlayPauseButton();
                if (isPlaying) {
                    startHideControlsTimer(); // 开始隐藏计时器
                } else {
                    stopHideControlsTimer(); // 停止隐藏计时器
                }
            }
        });

        // 设置默认播放速度
        player.setPlaybackSpeed(1.0f);
    }

    private String getFileName(Uri uri) {
        String fileName = "未知视频";
        ContentResolver contentResolver = getContentResolver();
        String mimeType = contentResolver.getType(uri);

        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            // 文件系统URI
            fileName = new File(uri.getPath()).getName();
        } else {
            // 其他类型URI，尝试从URI获取文件名
            String path = uri.getLastPathSegment();
            if (path != null) {
                fileName = path;
            }
        }
        return fileName;
    }

    private void togglePlayPause() {
        if (player == null) {
            if (currentVideoUri == null) {
                Toast.makeText(this, R.string.error_no_video_selected, Toast.LENGTH_SHORT).show();
            } else {
                preparePlayer(currentVideoUri);
            }
            return;
        }

        if (player.isPlaying()) {
            player.pause();
        } else {
            player.play();
        }
    }

    private void updatePlayPauseButton() {
        if (player != null) {
            if (player.isPlaying()) {
                playPauseButton.setText(R.string.pause);
            } else {
                playPauseButton.setText(R.string.play);
            }
        }
    }

    private void startProgressTimer() {
        stopProgressTimer();
        progressTimer = new Timer();
        progressTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> updateProgress());
            }
        }, 0, 1000);
    }

    private void stopProgressTimer() {
        if (progressTimer != null) {
            progressTimer.cancel();
            progressTimer = null;
        }
    }

    private void updateProgress() {
        if (player != null) {
            long currentPosition = player.getCurrentPosition();
            long duration = player.getDuration();

            if (duration > 0) {
                int progress = (int) (currentPosition * 100 / duration);
                progressBar.setProgress(progress);
            }

            currentTimeView.setText(formatTime(currentPosition));
        }
    }

    private void updateTotalTime() {
        if (player != null) {
            long duration = player.getDuration();
            totalTimeView.setText(formatTime(duration));
        }
    }

    private String formatTime(long milliseconds) {
        if (milliseconds < 0) return "00:00";
        long totalSeconds = milliseconds / 1000;
        long minutes = totalSeconds / 60;
        long seconds = totalSeconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    private void enterFullscreen() {
        // 隐藏系统UI
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }

        // 显示自定义控制
        customControls.setVisibility(View.VISIBLE);
        isControlsVisible = true;
        // 添加null检查，防止空指针异常
        if (chooseFileButton != null) {
            chooseFileButton.setVisibility(View.GONE);
        }

        // 设置全屏状态标志
        isFullscreen = true;

        // 更新方向
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        
        // 重置隐藏计时器
        resetHideControlsTimer();
    }

    private void exitFullscreen() {
        // 显示系统UI
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (getSupportActionBar() != null) {
            getSupportActionBar().show();
        }

        // 隐藏自定义控制
        customControls.setVisibility(View.GONE);
        isControlsVisible = false;
        // 添加null检查，防止空指针异常
        if (chooseFileButton != null) {
            chooseFileButton.setVisibility(View.VISIBLE);
        }

        // 重置全屏状态标志
        isFullscreen = false;

        // 更新方向
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        // 停止隐藏计时器
        stopHideControlsTimer();
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 处理屏幕旋转
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE && !isFullscreen) {
            enterFullscreen();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT && isFullscreen) {
            exitFullscreen();
        }
    }

    private void releasePlayer() {
        stopProgressTimer();
        stopHideControlsTimer(); // 停止控制栏隐藏计时器
        if (player != null) {
            player.release();
            player = null;
        }
    }
    
    // 显示/隐藏控制栏
    private void toggleControlsVisibility() {
        if (isControlsVisible) {
            hideControls();
        } else {
            showControls();
        }
    }
    
    // 显示控制栏
    private void showControls() {
        customControls.setVisibility(View.VISIBLE);
        isControlsVisible = true;
        resetHideControlsTimer();
    }
    
    // 隐藏控制栏
    private void hideControls() {
        customControls.setVisibility(View.GONE);
        isControlsVisible = false;
        stopHideControlsTimer();
    }
    
    // 开始控制栏隐藏计时
    private void startHideControlsTimer() {
        resetHideControlsTimer();
    }
    
    // 重置控制栏隐藏计时器
    private void resetHideControlsTimer() {
        stopHideControlsTimer();
        
        hideControlsTimer = new Timer();
        hideControlsTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> {
                    if (player != null && player.isPlaying()) {
                        hideControls();
                    }
                });
            }
        }, 3000); // 3秒后隐藏
    }
    
    // 停止控制栏隐藏计时器
    private void stopHideControlsTimer() {
        if (hideControlsTimer != null) {
            hideControlsTimer.cancel();
            hideControlsTimer = null;
        }
    }
    
    // 返回主界面
    private void returnToMainScreen() {
        // 停止播放
        if (player != null) {
            player.pause();
        }
        
        // 隐藏播放器，显示主内容
        playerView.setVisibility(View.GONE);
        customControls.setVisibility(View.GONE);
        isControlsVisible = false;
        findViewById(R.id.content_container).setVisibility(View.VISIBLE);
        
        // 恢复系统UI
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (getSupportActionBar() != null) {
            getSupportActionBar().show();
        }
        
        // 停止计时器
        stopHideControlsTimer();
    }
    
    // 快退功能（后退10秒）
    private void rewind() {
        if (player != null) {
            long currentPosition = player.getCurrentPosition();
            long newPosition = Math.max(0, currentPosition - 10000); // 后退10秒，最小为0
            player.seekTo(newPosition);
            updateProgress(); // 更新进度显示
        }
    }
    
    // 快进功能（前进10秒）
    private void fastForward() {
        if (player != null) {
            long currentPosition = player.getCurrentPosition();
            long duration = player.getDuration();
            long newPosition = Math.min(duration, currentPosition + 10000); // 前进10秒，最大为总时长
            player.seekTo(newPosition);
            updateProgress(); // 更新进度显示
        }
    }
    
    // 切换静音状态
    private void toggleMute() {
        if (player != null) {
            isMuted = !isMuted;
            if (isMuted) {
                player.setVolume(0f);
                if (muteButton != null) {
                    muteButton.setText("🔇"); // 静音图标
                }
            } else {
                player.setVolume(1f);
                if (muteButton != null) {
                    muteButton.setText("🔊"); // 非静音图标
                }
            }
        }
    }
    
    @Override
    public void onBackPressed() {
        // 如果正在播放视频，返回主界面
        if (playerView.getVisibility() == View.VISIBLE) {
            returnToMainScreen();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (Util.SDK_INT >= 24) {
            if (currentVideoUri != null) {
                preparePlayer(currentVideoUri);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (Util.SDK_INT < 24) {
            releasePlayer();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (Util.SDK_INT >= 24) {
            releasePlayer();
        }
    }

    private void openSettings() {
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }
    
    private void loadSameDirectoryVideos(Uri videoUri) {
        sameDirectoryVideos.clear();
        currentVideoIndex = -1;
        
        // 只处理文件系统URI
        if (ContentResolver.SCHEME_FILE.equals(videoUri.getScheme())) {
            File videoFile = new File(videoUri.getPath());
            File directory = videoFile.getParentFile();
            
            if (directory != null && directory.exists() && directory.isDirectory()) {
                File[] files = directory.listFiles((dir, name) -> {
                    String lowerName = name.toLowerCase();
                    return lowerName.endsWith(".mp4") || lowerName.endsWith(".mkv") || 
                           lowerName.endsWith(".avi") || lowerName.endsWith(".mov") ||
                           lowerName.endsWith(".wmv") || lowerName.endsWith(".flv");
                });
                
                if (files != null) {
                    // 按文件名排序
                    Arrays.sort(files, (f1, f2) -> f1.getName().compareToIgnoreCase(f2.getName()));
                    
                    for (int i = 0; i < files.length; i++) {
                        sameDirectoryVideos.add(files[i].getAbsolutePath());
                        if (files[i].getAbsolutePath().equals(videoFile.getAbsolutePath())) {
                            currentVideoIndex = i;
                        }
                    }
                }
            }
        }
    }
    
    private void playNextVideo() {
        if (sameDirectoryVideos != null && !sameDirectoryVideos.isEmpty() && currentVideoIndex >= 0) {
            int nextIndex = currentVideoIndex + 1;
            if (nextIndex < sameDirectoryVideos.size()) {
                String nextVideoPath = sameDirectoryVideos.get(nextIndex);
                Uri nextVideoUri = Uri.fromFile(new File(nextVideoPath));
                
                // 延迟一点播放下一个视频
                new Thread(() -> {
                    try {
                        Thread.sleep(500); // 500ms延迟
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    
                    runOnUiThread(() -> {
                        currentVideoUri = nextVideoUri;
                        preparePlayer(currentVideoUri);
                        player.play();
                    });
                }).start();
            }
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        releasePlayer();
    }
}